<?php

namespace backend\controllers;

use bc\controller\BackendController;
use bc\model\source\StatisticsModel;
use bc\model\source\LogModel;
use bc\util\backend\Page;
use bc\util\Uploader;

class SourceStatisticsController extends BackendController
{
	public function actionIndex()
	{
		$start_time = $this->get ( 'start_time' );
		$end_time = $this->get ( 'end_time' );
		
		$model = new StatisticsModel ();
		$params = '1 = 1';
		
		$page = $this->get ( 'page', 1 );
		$list = $model->getList ( $params, $page, self::PAGE_SIZE );
		
		if ($start_time || $end_time)
		{
			foreach ( $list as $key => $item )
			{
				$list [$key] ['num'] = $this->analysis ( $item ['id'], $start_time, $end_time );
			}
		}
		
		$total = $model->getTotal ( $params );
		
		$pagination = new Page ( $total, self::PAGE_SIZE );
		
		$view ['list'] = $list;
		$view ['pagination'] = $pagination;
		
		$view ['start_time'] = $start_time;
		$view ['end_time'] = $end_time;
		
		return $this->render ( 'index', $view );
	}
	
	/**
	 * 
	 */
	public function actionAdd()
	{
		return $this->render ( 'add' );
	}
	
	/**
	 */
	public function actionEdit()
	{
		$id = $this->get ( 'id' );
		if (! $id)
			$this->redirect ( '/' );
		
		$model = new StatisticsModel ();
		$row = $model->getRowById ( $id );
		
		if (! $row)
			$this->redirect ( '/' );
		
		$view ['row'] = $row;
		
		return $this->render ( 'edit', $view );
	}
	
	/**
	 */
	public function actionShow()
	{
		$id = $this->get ( 'id' );
		if (! $id)
			$this->redirect ( '/' );
		
		$model = new StatisticsModel ();
		$row = $model->getRowById ( $id );
		
		if (! $row)
			$this->redirect ( '/' );
		
		$params = 'statistics_id = ' . $id;
		
		$start_time = $this->get ( 'start_time' );
		$end_time = $this->get ( 'end_time' );
		
		if ($start_time)
		{
			$params .= ' and create_time >= ' . strtotime ( $start_time );
		}
		
		if ($end_time)
		{
			$params .= ' and create_time <= ' . strtotime ( $start_time );
		}
		
		$page = $this->get ( 'page', 1 );
		$logModel = new LogModel ();
		$logModel->autoId = 'statistics_log_id';
		$list = $logModel->getList ( $params, $page, self::PAGE_SIZE );
		
		$total = $logModel->getTotal ( $params );
		
		$pagination = new Page ( $total, self::PAGE_SIZE );
		
		$view ['list'] = $list;
		$view ['pagination'] = $pagination;
		
		$view ['row'] = $row;
		$view ['start_time'] = $start_time;
		$view ['end_time'] = $end_time;
		$view ['id'] = $id;
		
		return $this->render ( 'show', $view );
	}
	public function actionSave()
	{
		if ($this->getRequest ()->getMethod () === 'POST')
		{
			$model = new StatisticsModel ();
			$id = $this->post ( 'id', 0 );
			
			$data ['description'] = $this->post ( 'description', '' );
			$data ['link'] = $this->post ( 'link', '' );
			$data ['update_time'] = time ();
			
			$data ['status'] = $this->post ( 'status' );
			
			// 上传图片
			if ($_FILES ['image'])
			{
				$up = new Uploader ( 'image', $this->getUploadConfig () );
				$info = $up->getFileInfo ();
				if ($info ['state'] === 'SUCCESS')
				{
					$data ['image'] = str_replace ( UPLOAD_PATH, '', $info ['url'] );
				}
			}
			
			if ($id)
			{
				$model->modify ( $data, $id );
			}
			else
			{
				$data ['create_time'] = time ();
				$id = $model->add ( $data );
				// 获取生成二维码的地址
				$qrcod_file = $this->createQrcode ( $id );
				// 写入二维码图片路径
				$model->modify ( [ 
						'qrcode_file' => $qrcod_file 
				], $id );
			}
			$output ['msg'] = '操作成功!';
		}
		else
		{
			$output ['msg'] = '非法请求!';
		}
		
		$output ['url'] = '/source-statistics';
		$this->forward ( $output );
	}
	
	/**
	 *
	 * @return array
	 */
	private function getUploadConfig()
	{
		// 上传文件目录
		$path = UPLOAD_PATH . 'upload/';
		// 上传配置
		$config = array (
				"savePath" => $path, // 存储文件夹
				"maxSize" => 100000, // 允许的文件最大尺寸，单位KB
				"allowFiles" => array (
						".gif",
						".png",
						".jpg",
						".jpeg",
						".bmp" 
				) 
		); // 允许的文件格式

		
		// 背景保存在临时目录中
		$config ["savePath"] = $path;
		return $config;
	}
	
	/**
	 * 创建二维码
	 *
	 * @return string path
	 */
	private function createQrcode($id)
	{
		$value = 'http://wx.zhishimama.com/source-statistics/index?id=' . $id;
		$errorCorrectionLevel = 'L';
		$matrixPointSize = '10';
		
		$basePath = 'qrcode/';
		
		$time = time ();
		
		$filePath = UPLOAD_PATH . $basePath;
		$this->createDir ( $filePath );
		$png_file = $filePath . $time . '.png';
		
		include_once (ROOT_PATH . "/vendor/phpqrcode/phpqrcode.php");
		
		\QRcode::png ( $value, $png_file, $errorCorrectionLevel, $matrixPointSize );
		
		return $basePath . $time . '.png';
	}
	
	/**
	 * 递归创建目录
	 *
	 * @param string $path        	
	 */
	private function createDir($path)
	{
		if (! file_exists ( $path ))
		{
			$this->createDir ( dirname ( $path ) );
			mkdir ( $path, 0777 );
		}
	}
	
	/**
	 *
	 * @param int $id        	
	 * @param string $start_time        	
	 * @param string $end_time        	
	 */
	private function analysis($id, $start_time, $end_time)
	{
		$total = 0;
		$beginTime = strtotime ( $start_time );
		$endTime = strtotime ( $end_time );
		$logModel = new LogModel ();
		$total = $logModel->analysis ( $id, $beginTime, $endTime );
		return $total;
	}
}

